define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'car/old/index' + location.search,
                    add_url: 'car/old/add',
                    edit_url: 'car/old/edit',
                    del_url: 'car/old/del',
                    multi_url: 'car/old/multi',
                    import_url: 'car/old/import',
                    table: 'car_old',
                }
            });

            var table = $("#table");
            //归属人
            table.on('post-common-search.bs.table', function (event, table) {
                let form = $("form", table.$commonsearch);
                $("input[name='user_id']", form).addClass("selectpage").data("source", "user/user/searchlist2").data("primaryKey", "id").data("field", "name").data("orderBy", "id");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                fixedNumber:7,
                showExport:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: '车源编号', operate: 'LIKE'},
                        {field: 'nickname', title: "归属人", operate: false},
                        // {
                        //     field: 'user_id',
                        //     title: '归属人',
                        //     operate: '=',
                        //     table: table,
                        //     searchList: $.getJSON("user/user/searchlist"),
                        //     visible:false,
                        //     formatter: Table.api.formatter.search
                        // },
                        {field: 'user_id', operate: '=', title: '归属人', placeholder: '归属人',visible:false,formatter: Table.api.formatter.dav_config},
                        {
                            field: 'type',
                            title: "车源分类",
                            searchList: {"0": "二手车", "1": "新车"},
                            formatter: Table.api.formatter.label
                        },
                        {field: 'car_brand_name', title: __('Car_brand_id')},
                        {field: 'car_series_name', title: __('Car_series_id')},
                        {
                            field: 'car_models_name',
                            title: __('Car_models_id'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },

                        {field: 'city', title: __('地区'), operate: 'LIKE', searchList: function (column) {
                                return Template('categorytpl', {});
                            }, formatter: function (value, row, index) {
                                return value;
                            }, visible: true
                        },
                        {
                            field: 'VIN',
                            title: __('Vin'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {field: 'cc', title: __('Cc'), operate: 'BETWEEN'},
                        {
                            field: 'cc_unit',
                            title: __('Cc_unit'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },

                        {
                            field: 'car_image',
                            title: __('Car_image'),
                            operate: false,
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image
                        },
                        {field: 'prove_image', title: '车辆铭牌', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},

                        // {field: 'car_video', title: __('Car_video'), operate: 'false',previewfile:true},


                        // {
                        //     field: 'registration_time',
                        //     title: __('Registration_time'),
                        //     operate: 'RANGE',
                        //     addclass: 'datetimerange',
                        //     autocomplete: false
                        // },
                        // {field: 'factory_date', title: __('Factory_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},

                        {field: 'cut_price', title: "调整前价格", operate: 'BETWEEN'},
                        {field: 'price', title: __('Price'), operate: 'BETWEEN'},
                        {field: 'base_price', title: __('Base_price'), operate: 'BETWEEN'},
                        // {
                        //     field: 'is_price',
                        //     title: __('Is_price'),
                        //     searchList: {"0": "否", "1": "是"},
                        //     formatter: Table.api.formatter.status
                        // },
                        {field: 'transfer_num', title: __('Transfer_num')},
                        {field: 'odometer_km', title: __('Odometer_km'), operate: 'BETWEEN'},
                        // {
                        //     field: 'year_inspect_date',
                        //     title: __('Year_inspect_date'),
                        //     operate: 'RANGE',
                        //     addclass: 'datetimerange',
                        //     autocomplete: false
                        // },
                        {
                            field: 'compulsory_insurance_date',
                            title: __('Compulsory_insurance_date'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false
                        },
                        // {
                        //     field: 'mortgage',
                        //     title: __('Mortgage'),
                        //     searchList: {"0": "无抵押", "1": "有抵押"},
                        //     formatter: Table.api.formatter.label
                        // },
                        {
                            field: 'use_character',
                            title: __('Use_character'),
                            searchList: {"0": "非营运", "1": "网约车退役"},
                            formatter: Table.api.formatter.label
                        },
                        {
                            field: 'car_describe',
                            title: __('Car_describe'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        // {field: 'label_ids', title: __('Label_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'sparkle_ids', title: __('Sparkle_ids'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'key_num', title: __('Key_num')},
                        // {field: 'spare_tire', title: __('Spare_tire'), operate: 'LIKE'},
                        // {field: 'car_colour', title: __('Car_colour'), operate: 'LIKE'},
                        // {field: 'prove_image', title: __('Prove_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'test_report_file', title: __('Test_report_file'), operate: false, formatter: Table.api.formatter.file},
                        {field: 'ssss_report_image', title: __('Ssss_report_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'danger_report_image', title: __('Danger_report_image'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},

                        {field: 'defect_images', title: '瑕疵照片', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'odometer_images', title: '里程表图片', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},


                        // {field: 'gearbox', title: __('Gearbox')},
                        // {field: 'new_price', title: __('New_price'), operate:'BETWEEN'},
                        // {field: 'load_people_num', title: __('Load_people_num')},
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        // {
                        //     field: 'recommend',
                        //     title: "推荐",
                        //     align: 'center',
                        //     table: table,
                        //     formatter: Table.api.formatter.toggle,
                        //     operate: false
                        // },
                        // {
                        //     field: 'hot_search',
                        //     title: "热搜",
                        //     align: 'center',
                        //     table: table,
                        //     formatter: Table.api.formatter.toggle,
                        //     operate: false
                        // },
                        // {
                        //     field: 'hot_sales',
                        //     title: "热销",
                        //     align: 'center',
                        //     table: table,
                        //     formatter: Table.api.formatter.toggle,
                        //     operate: false
                        // },

                        {
                            field: 'status',
                            title: "上架/下架",
                            align: 'center',
                            table: table,
                            formatter: Table.api.formatter.toggle,
                            searchList: {"0": "下架", "1": "上架"}
                            //operate: false
                        },
                        {
                            field: 'operate',
                            title: "权重",
                            table: table,
                            width:500,
                            events: Table.api.events.operate,
                            formatter: function (value, row, index) {
                                return "<div style='color: green'>"+row.weight+"</div><button onclick='weightEdit(" + row.id + "," + row.weight + ")'   class='shenhe btn-success'>编辑</button>"

                            }
                        },

                        // {field: 'verify_status', title: "审核状态", searchList: {"0":"未审核","1":"通过","2":"驳回"}, formatter: Table.api.formatter.status},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });




            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});


$("#car_brand_id").data("params", function (obj) {
    //obj为SelectPage对象
    let val = $("#c-car_brand_name").val()
    console.log(val)
    return {custom: {queryarr: val}};
});

$("#c-car_series_id").data("params", function (obj) {
    //obj为SelectPage对象
    return {custom: {brand_id: $("#c-car_brand_id").val()}};
});

$("#c-car_models_id").data("params", function (obj) {
    //obj为SelectPage对象
    return {custom: {series_id: $("#c-car_series_id").val()}};
});

$("#c-car_brand_id").change(function () {
    let val = $("input[name='row[car_brand_id]_text']").val()
    $("#c-car_brand_name").val(val)
})

$("#c-car_series_id").change(function () {
    let val = $("input[name='row[car_series_id]_text']").val()
    $("#c-car_series_name").val(val)
})
$("#c-car_models_id").change(function () {
    let val = $("input[name='row[car_models_id]_text']").val()
    $("#c-car_models_name").val(val)
})

$("#c-car_brand_type_id").change(function () {
    let val = $("input[name='row[car_brand_type_id]_text']").val()
    $("#c-car_brand_type_name").val(val)
})

function tui() {
    var temp = $("#table").bootstrapTable('getSelections')
    var ids = []
    if (temp.length > 0) {
        temp.forEach((item)=>{
            ids.push(item.id)
        })
    }
    layer.confirm(`确定该操作吗？`, {
            title: "热推",
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            $.ajax({
                url: "car/old/tui", //请求接口
                type: "post",
                dataType: "json",
                data: {"ids": ids}, //请求参数
                success: function (data) {
                    layer.confirm(data.msg, {
                        btn: ['确定'] //按钮
                    }, function (index2) {
                        Fast.api.refreshmenu(); //刷新列表
                        layer.close(index2); //关闭窗口
                    })
                    return false;
                }
            })

        }
    );
}

function sou() {
    var temp = $("#table").bootstrapTable('getSelections')
    var ids = []
    if (temp.length > 0) {
        temp.forEach((item)=>{
            ids.push(item.id)
        })
    }
    layer.confirm(`确定该操作吗？`, {
            title: "热推",
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            $.ajax({
                url: "car/old/sou", //请求接口
                type: "post",
                dataType: "json",
                data: {"ids": ids}, //请求参数
                success: function (data) {
                    layer.confirm(data.msg, {
                        btn: ['确定'] //按钮
                    }, function (index2) {
                        Fast.api.refreshmenu(); //刷新列表
                        layer.close(index2); //关闭窗口
                    })
                    return false;
                }
            })

        }
    );
}
function xiao() {
    var temp = $("#table").bootstrapTable('getSelections')
    var ids = []
    if (temp.length > 0) {
        temp.forEach((item)=>{
            ids.push(item.id)
        })
    }
    layer.confirm(`确定该操作吗？`, {
            title: "热推",
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            $.ajax({
                url: "car/old/xiao", //请求接口
                type: "post",
                dataType: "json",
                data: {"ids": ids}, //请求参数
                success: function (data) {
                    layer.confirm(data.msg, {
                        btn: ['确定'] //按钮
                    }, function (index2) {
                        Fast.api.refreshmenu(); //刷新列表
                        layer.close(index2); //关闭窗口
                    })
                    return false;
                }
            })

        }
    );
}

//生成海报

// r: 半径
function circleImg(ctx, img, x, y,width,height, radius) {

    ctx.save()
    // 开始路径并移动到起点位置
    ctx.beginPath();
    ctx.moveTo(x + radius, y);

    // 从右上角开始绘制圆角
    ctx.lineTo(x+width - radius, y);
    ctx.arc(x+width - radius, y + radius, radius, -Math.PI / 2, 0); // 从右边绘制圆角

    // 从右下角开始绘制圆角
    ctx.lineTo(x+width, y+height - radius);
    ctx.arc(x+width - radius, y+height - radius, radius, 0, Math.PI / 2); // 从底部绘制圆角

    // 从左下角开始绘制圆角
    ctx.lineTo(x+radius, y+height);
    ctx.arc(x+radius, y+height - radius, radius, Math.PI / 2, Math.PI); // 从左边绘制圆角

    ctx.lineTo(x,y+radius)
    ctx.arc(x+radius, y + radius, radius, -Math.PI, -Math.PI/2);
    // 最后连接起点与第一条直线
    ctx.closePath();
    // clip方法重要
    ctx.clip();
    ctx.drawImage(img, x, y, width, height );
    ctx.restore()

}
function haibao() {

    var temp = $("#table").bootstrapTable('getSelections')
    console.log(temp)
    var ids = []
    if (temp.length > 1) {
        layer.msg("只能选择一个")
        return
    }
    layer.open({
        type: 1,
        title: '海报',
        content: $('#haibao'),
        area: ['430px', '850px']
    });

    let val = temp[0]

    const canvas = document.getElementById('poster-canvas');
    const context = canvas.getContext('2d');

    const backgroundImage = new Image();
    backgroundImage.src = '../../assets/img/zy/bj.jpg';

    backgroundImage.onload = function() {
        context.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);

        let arr = val.car_image.split(",");
        if (arr.length <= 0) {
            layer.msg("未找到封面图")
            return
        }

        $.get('car/old/masterimgurl?url='+'https://oss.taochewa.com'+arr[0], function(data) {
            const che = new Image()
            che.src = data
            che.onload = function() { //车
                // ========车



                circleImg(context,che,58, 134, 315, 220,15)
                // context.drawImage(che, 58, 134, 315, 220);
                // ========车

                //已售罄
                context.save(); // 保存当前图层状态
                const zhang = new Image()
                zhang.src = '../../assets/img/zy/zhang.png'
                zhang.onload = function() {
                    context.drawImage(zhang, 290, 320, 125, 125);

                };
                // 恢复第一个图层的状态，以便第二个图层显示在蓝色圆的上面
                context.restore();


            };
        });



        // let text = val.car_series_name + " " +val.car_models_name;
        let text = val.car_models_name;
        context.font = 'bold 16px Arial';
        context.fillStyle = 'black'; // 设置填充颜色
        context.fillText(text, 60, 117);

        text = '出厂日期:'+val.factory_date;
        context.font = '14px Arial';
        context.fillStyle = 'black'; // 设置填充颜色
        context.fillText(text, 60, 380);

        let unit = "自然吸气"
        if (val.cc_unit === "T") {
            unit = "涡轮增压"
        }


        text = '排量:'+val.cc+val.cc_unit+unit+' 公里数:'+val.odometer_km+'万公里';
        context.font = '14px Arial';
        context.fillStyle = 'black'; // 设置填充颜色
        context.fillText(text, 60, 400);

    };



}
// 生成有圆角的矩形
function drawRoundedRect(cxt, x, y, width, height, radius) {
    cxt.beginPath();
    cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2);
    cxt.lineTo(width - radius + x, y);
    cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2);
    cxt.lineTo(width + x, height + y - radius);
    cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2);
    cxt.lineTo(radius + x, height + y);
    cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI);
    cxt.closePath();
}


function baocun() {
    // 保存图片
    var canvas = document.getElementById("poster-canvas");
    // const MIME_TYPE = "image/png";
    // const imgURL = canvas.toDataURL(MIME_TYPE);
    //
    // // 创建一个隐藏的 a 标签
    // const dlLink = document.createElement("a");
    // const filename = "个人画板_" + new Date().getTime() + ".png";
    //
    // // 设置下载文件名和链接的 href 属性
    // dlLink.download = filename;
    // dlLink.href = imgURL;
    //
    // // 触发下载
    // document.body.appendChild(dlLink);
    // dlLink.click();
    // document.body.removeChild(dlLink);
    // return



    const posterImage = canvas.toDataURL('image/png');
    const posterElement = document.createElement('img');
    posterElement.src = posterImage;

    //document.body.appendChild(posterElement);
    const link = document.createElement('a');
    link.href = posterImage;
    link.download = 'poster.png';
    link.click();

    // Fast.api.refreshmenu(); //刷新列表
    // layer.closeAll(); //关闭窗口
}

function weightEdit(id,weight) {
    layer.open({
        type: 1,
        title: '申诉通知',
        content: $('#popup'),
        area: ['400px', '150px']
    });
    $("#ids").val(id)
    $("#weight").val(weight)
}

$("#tongzhipost").click(function () {
    let weight = $("#weight").val()
    let id = $("#ids").val()
    $.ajax({
        url: "car/old/weight", //请求接口
        type: "post",
        dataType: "json",
        data: {
            "id": id,
            "weight": weight
        }, //请求参数
        success: function (data) {
            Fast.api.refreshmenu(); //刷新列表
            layer.closeAll(); //关闭窗口

            return false;
        }
    })

})
